package com.dp.common;

import com.dp.entity.User;
import com.dp.mapper.UserMapper;
import com.dp.util.MybatisPlusUtil;
import com.google.gson.Gson;
import org.apache.ibatis.session.SqlSession;
import redis.clients.jedis.Jedis;

import java.util.List;

public class Redis {

    public User getUser(Integer id){
        //连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        String key = "user";
        List<String> list = jedis.lrange(key, 0, -1);
        Gson gson = new Gson();

        // 检查用户数据是否存在于缓存中
        if (jedis.exists(key)) {
            // 使用del()方法删除与用户数据关联的键
            jedis.del(key);
        }



        SqlSession session = MybatisPlusUtil.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);

        User user = userMapper.selectById(id);

        String userJson = gson.toJson(user);

        jedis.lpush(key, userJson);

        // 从redis中获取list
        list = jedis.lrange(key, 0, -1);


        user = gson.fromJson( list.get(0) ,User.class);

        return user;

    }
}
